package com.guozcc.bootweb.platform.config.mybatis;


import com.alibaba.fastjson.JSONObject;
import org.apache.ibatis.reflection.MetaObject;
import org.apache.ibatis.reflection.wrapper.MapWrapper;
import org.apache.ibatis.reflection.wrapper.ObjectWrapper;
import org.apache.ibatis.reflection.wrapper.ObjectWrapperFactory;
import org.apache.ibatis.session.Configuration;
import org.mybatis.spring.boot.autoconfigure.ConfigurationCustomizer;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;

import java.util.Map;

@Component
public class ResultToLowerCaseFactory implements ObjectWrapperFactory {
    @Override
    public boolean hasWrapperFor(Object o) {
        return o instanceof Map;
    }

    @Override
    public ObjectWrapper getWrapperFor(MetaObject metaObject, Object o) {
        return new ResultToLowerCase(metaObject, (Map) o);
    }

    /**
     *  使用该方式object-wrapper-factory: com.demo.config.SqlFieldToLowerCaeFactory
     *  会报类型转换异常所以使用下面这种方式
     * @return
     */
//    @Bean
//    public ConfigurationCustomizer mybatisConfigurationCustomizer() {
//        return new ConfigurationCustomizer() {
//            @Override
//            public void customize(Configuration configuration) {
//                configuration.setObjectWrapperFactory(new ResultToLowerCaseFactory());
//            }
//        };
//    }


    class ResultToLowerCase extends MapWrapper {

        public ResultToLowerCase(MetaObject metaObject, Map<String, Object> map) {
            super(metaObject, map);
        }

        @Override
        public String findProperty(String name, boolean useCamelCaseMapping) {
            if (useCamelCaseMapping) {
                //查询字段转小写
                return name == null ? null : name.toLowerCase();
            }
            return name;
        }


    }

}

